import { defineStore } from "pinia";
import { reqLogin, reqUserInfo, reqLogout, reqUserMenu } from "@/api/user";
import { logfromType, logfromDate, userInfoData } from "./type";

import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/uitls/token";
import { constantRoute, asnycRoute, anyRoute } from "@/router/routes";
import router, { resetRouter } from "@/router";
//@ts-expect-error
import cloneDeep from "lodash/cloneDeep";
function filterAsyncRoute(asnycRoute1: any, routes: any) {
  return asnycRoute1.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  });
}

const userInfo = defineStore("user", {
  state() {
    return {
      token: GET_TOKEN(),
      username: "",
      avatar: "",
      //存储当前用户是否包含某一个按钮
      buttons: [],
      menuRoutes: constantRoute,
      checkUserRoutes: [], //用户权限
      rolebuttons: [], //用户按钮权限
    };
  },
  actions: {
    // 登录
    async userLogin(data: logfromType) {
      const result: logfromDate = await reqLogin(data);
      console.log(result, "res");
      if (result.code == 200) {
        SET_TOKEN(result.data);
        this.token = result.data;
        return "ok";
      } else {
        return Promise.reject(result);
      }
    },
    // 获取用户信息
    async userGetInfo() {
      const result: userInfoData = await reqUserInfo();
      if (result.code == 200) {
        const { data } = result;
        this.username = data.name;
        this.avatar = data.avatar;
        // 获取用户信息成功后获取该用户router
        console.log("当前登录角色权限信息", data);
        // 获取动态菜单
        // const res = await reqUserMenu();

        const userAsyncRoute = filterAsyncRoute(
          // cloneDeep(res.data.menuList),
          cloneDeep(asnycRoute),
          data.routes
        );
        console.log(userAsyncRoute, "userAsyncRoute");

        this.checkUserRoutes = data.routes;
        this.rolebuttons = data.buttons;
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute];
        // this.menuRoutes = [...constantRoute,...userAsyncRoute, anyRoute];
        this.menuRoutes.forEach((route: any) => {
          router.addRoute(route);
        });
        await resetRouter(this.menuRoutes);
        // console.log('当前角色全部路由', this.menuRoutes);

        return "ok";
      } else {
        return Promise.reject(result.data);
      }
    },
    // 推出登录
    async userLogout() {
      const result: any = await reqLogout();
      if (result.code == 200) {
        this.token = "";
        this.username = "";
        this.avatar = "";
        REMOVE_TOKEN();
        return "ok";
      } else {
        return Promise.reject(result.data);
      }
    },
  },
});
export default userInfo;
